package com.zj.controller;

import com.zj.bean.CommonConfig;
import com.zj.data.DataCenter;
import com.zj.util.JsonUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

@FXMLController
public class ProjectConfigCtl implements Initializable {

    public TextArea configArea;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.configArea.setText(JsonUtil.obj2PrettyString(DataCenter.getData("commonConfig", CommonConfig.class)));
    }

    public void saveConfig(ActionEvent actionEvent) {
        File configFile= DataCenter.getData("commonConfigFile",File.class);
        try {
            CommonConfig commonConfig = JsonUtil.prettyToObject(configArea.getText(),CommonConfig.class);
            FileUtils.writeStringToFile(configFile, JsonUtil.obj2String(commonConfig),"utf-8");
            DataCenter.saveData("commonConfig",commonConfig);
            ((Stage)((Button)actionEvent.getSource()).getScene().getWindow()).close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close(ActionEvent actionEvent) {
        ((Stage)((Button)actionEvent.getSource()).getScene().getWindow()).close();
    }
}
